/**
 * Copyright (c) OpenSpug Organization. https://github.com/openspug/spug
 * Copyright (c) <spug.dev@gmail.com>
 * Released under the AGPL-3.0 License.
 */
import React from 'react';
import {observer} from 'mobx-react';
import {Table, Divider, Modal, Badge, message, Form, Input} from 'antd';
import {LinkButton} from 'components';
import ComForm from './Form';
import http from 'libs/http';
import store from './store';
import FormatPic from "../../../components/formater/FormatPic";
import {BanUser, DeleteUser, ResetPassword} from "../../../api/system/account/UserApi";
import RoleForm from "./RoleForm";

@observer
class UserTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      password: ''
    }
  }
  componentDidMount() {
    store.fetchRecords()
  }

  columns = [
    {
      title: '序号',
      key: 'series',
      render: (_, __, index) => index + 1,
      width: 80
    },
    {
      title: '登录名',
      dataIndex: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
    },
    {
      title: '邮箱',
      dataIndex: 'email'
    },
    {
      title: '状态',
      render: text => text['is_active'] === 1 ? <Badge status="success" text="正常"/> : <Badge status="default" text="禁用"/>
    },
    {
      title: '最近登录',
      dataIndex: 'last_login_time'
    },
    {
      title: '操作',
      render: info => (
        <span>
          <LinkButton className="span-button" onClick={() => this.handleActive(info)}>{info['is_active'] === 1 ? '禁用' : '启用'}</LinkButton>
          <Divider type="vertical"/>
          <LinkButton className="span-button" onClick={() => this.handleEdit(info)}>编辑</LinkButton>
          <Divider type="vertical"/>
          <LinkButton className="span-button" onClick={() => this.handleReset(info)}>重置密码</LinkButton>
          <Divider type="vertical"/>
          <LinkButton className="span-button" onClick={() => store.showRoleForm(info)}>分配角色</LinkButton>
          <Divider type="vertical"/>
          <LinkButton className="span-button" onClick={() => this.handleDelete(info)}>删除</LinkButton>
        </span>
      )
   }
  ];

  handleActive = (record) => {
    Modal.confirm({
      title: '操作确认',
      content: `确定要${record['is_active'] === 1 ? '禁用' : '启用'}【${record['nickname']}】?`,
      onOk: () => {
        BanUser({id: record.id}).then(response => {
          if (response.data.code === 200){
            message.success(response.data.msg);
            store.fetchRecords();
            return true;
          }
        });
      }
    })
  };
  
  handleEdit = (info)=>{
    store.showForm(info);
  };

  handleReset = (info) => {
    Modal.confirm({
      icon: 'exclamation-circle',
      title: '重置登录密码',
      content: <Form>
        <Form.Item required label="重置后的新密码">
          <Input.Password onChange={val => this.setState({password: val.target.value})}/>
        </Form.Item>
      </Form>,
      onOk: () => {
        ResetPassword({id: info.id, password: this.state.password}).then(response => {
          if (response.data.code === 200){
            message.success(response.data.msg);
          }
        });
      },
    })
  };

  handleDelete = (record) => {
    Modal.confirm({
      title: '删除确认',
      content: `确定要删除用户【${record['nickname']}】?`,
      onOk: () => {
        DeleteUser({id:record["id"]}).then(response => {
          if (response.data.code === 200){
            message.success('删除成功');
            store.fetchRecords()
          }
        });
      }
    })
  };

  render() {
    let data = store.records;
    if (store.f_name) {
      data = data.filter(item => item['username'].toLowerCase().includes(store.f_name.toLowerCase()))
    }
    if (store.f_status) {
      data = data.filter(item => String(item['is_active']) === store.f_status)
    }
    return (
      <React.Fragment>
        <Table
          rowKey="id"
          loading={store.isFetching}
          dataSource={data}
          pagination={{
            showSizeChanger: true,
            showLessItems: true,
            hideOnSinglePage: true,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
          columns={this.columns}/>
        {store.formVisible && <ComForm />}
        {store.roleFormVisible && <RoleForm />}
      </React.Fragment>
    )
  }
}

export default UserTable
